<template>
  <div class="add-approval">
    <div class="header">
      <!-- <h2>报题提交</h2> -->
    </div>
    <div class="content">
      <a-row :gutter="64">
        <a-col class="gutter-row" :span="10">
          <h2 style="font-weight:bold">报题内容</h2>

          <a-form-model ref="form" :model="form" :rules="rules">
            <a-form-model-item label="报题名称" prop="title">
              <a-input v-model="form.title" placeholder="请输入报题名称" />
            </a-form-model-item>

            <a-form-model-item label="工作成员" prop="work_members">
              <a-tree-select v-model="form.work_members" show-search style="width: 100%" treeNodeFilterProp="title"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" :tree-data="personListTree1" multiple
                placeholder="请选择工作成员">
              </a-tree-select>
            </a-form-model-item>

            <!-- <a-form-model-item label="产出类型" prop="output_types">
              <a-select v-model="form.output_types" mode="multiple" :default-value="[]" style="width: 100%"
                placeholder="请选择">
                <a-select-option :key="1" value="新媒体图文">
                  新媒体图文
                </a-select-option>
                <a-select-option :key="2" value="新媒体视频">
                  新媒体视频
                </a-select-option>
                <a-select-option :key="3" value="广播电视类">
                  广播电视类
                </a-select-option>
              </a-select>
            </a-form-model-item> -->

            <a-form-model-item label="产出类型" prop="output_types">
              <a-button-group class="output-btn-group">
                <a-button v-for="item in output_types_list" :key="item.value" :value="item.value"
                  :type="item.checked ? 'primary' : 'default'" @click="handleOutputChange(item.value)">
                  {{item.label}}
                </a-button>
              </a-button-group>
            </a-form-model-item>

            <a-form-model-item label="预计工期" prop="dateRange">
              <a-range-picker v-model="form.dateRange" @change="handleDateChange" :placeholder="['开始日期', '结束日期']" />
            </a-form-model-item>

            <a-form-model-item label="报题内容" prop="content">
              <a-textarea v-model="form.content" placeholder="请输入报题内容" :rows="4" />
            </a-form-model-item>
          </a-form-model>
        </a-col>
        <a-col class="gutter-row" :span="10" :offset="2">
          <h2 style="font-weight:bold">审批流程</h2>
          <a-timeline class="a-timeline-content" style="margin-top:64px">
            <!-- 发起 -->
            <a-timeline-item>
              <a-space>
                <a-avatar style="backgroundColor:#1890ff;" :size="64">{{personInfo.person_name}}</a-avatar>
                <span>【{{personInfo.person_name}}】发起</span>
              </a-space>
            </a-timeline-item>
            <!-- 一级 -->
            <a-timeline-item>
              <a-space>
                <a-avatar v-show="!approver1" :size="64" icon="plus"></a-avatar>
                <a-avatar style="margin-left:-8px;backgroundColor:#1890ff;" v-show="approver1" :size="64">
                  {{approver1Name}}</a-avatar>
                <span v-if="!approver1">请选择一级审批人（必选）</span>
                <span v-else>【{{approver1Name}}】一级审批（必选）</span>
              </a-space>
              <br>
              <a-tree-select v-model="approver1" show-search
                style="opacity: 0;position:absolute;transform: translateY(-48px);width: 64px" treeNodeFilterProp="title"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" :tree-data="approversByLevelTree1"
                placeholder="请选择一级审批人" @change="handleApprover1Change">
              </a-tree-select>
            </a-timeline-item>
            <!-- 二级 -->
            <a-timeline-item>
              <a-space>
                <a-avatar v-show="!approver2" :size="64" icon="plus"></a-avatar>
                <a-avatar style="margin-left:-8px;backgroundColor:#1890ff;" v-show="approver2" :size="64">
                  {{approver2Name}}</a-avatar>
                <span v-if="!approver2">请选择二级审批人（可选）</span>
                <span v-else>【{{approver2Name}}】二级审批（可选）</span>
              </a-space>
              <br>
              <a-tree-select v-model="approver2" show-search
                style="opacity: 0;position:absolute;transform: translateY(-48px);width: 64px" treeNodeFilterProp="title"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" :tree-data="approversByLevelTree2"
                placeholder="请选择二级审批人" @change="handleApprover2Change">
              </a-tree-select>
            </a-timeline-item>
          </a-timeline>
        </a-col>
      </a-row>
      <div class="submit-content">
        <a-button type="primary" :loading="submitting" @click="handleSubmit">
          提交
        </a-button>
        <a-button style="margin-left: 10px" @click="handleReset">
          重置
        </a-button>
      </div>
    </div>
  </div>
</template>

<script>
  import moment from 'moment'

  import {
    apiApprovalCreate,
    apiPersonGetAllListTree,
    apiFindApproversByLevelTree
  } from '@/api/featch'

  const personInfo = JSON.parse(window.sessionStorage.getItem('person_info') || '{}')


  export default {
    name: 'AddApproval',
    data() {
      return {
        personInfo,
        // 表单数据
        form: {
          title: '',
          work_members: [],
          content: '',
          output_types: [],
          estimated_start_date: null,
          estimated_end_date: null,
          dateRange: [],
        },
        output_types_list: [{
          value: 1,
          label: '新媒体图文',
          checked: false
        }, {
          value: 2,
          label: '新媒体视频',
          checked: false
        }, {
          value: 3,
          label: '广播电视类',
          checked: false
        }],
        approver1: null,
        approver1Name: null,
        approver2: null,
        approver2Name: null,

        // 表单验证规则
        rules: {
          title: [{
              required: true,
              message: '请输入报题名称',
              trigger: 'blur'
            },
            {
              min: 2,
              max: 100,
              message: '长度在 2 到 100 个字符',
              trigger: 'blur'
            }
          ],
          work_members: [{
            required: true,
            message: '请选择工作成员',
            trigger: 'change'
          }],
          dateRange: [{
            required: true,
            message: '请选择预计工期',
            trigger: 'change'
          }],
          content: [{
            required: true,
            message: '请输入报题内容',
            trigger: 'blur'
          }, ],
        },

        // 人员列表
        personListTree1: [],
        approversByLevelTree1: [],
        approversByLevelTree2: [],
        personLoading: false,

        // 提交状态
        submitting: false
      }
    },
    mounted() {
      this.getInitialPersonListTree()
      this.getFindApproversByLevelTree()
    },
    computed: {},
    methods: {
      /**
       * @description 产出类型改变时 钩子
       */
      handleOutputChange(e) {
        this.output_types_list.map((item, index) => {
          if (item.value == e) {
            this.$set(this.output_types_list[index], 'checked', !item.checked)
          }
          console.log(e)
          console.log(this.output_types_list)
        })
      },
      /**
       * @description 处理日期变化
       */
      handleDateChange(dates) {
        if (dates && dates.length === 2) {
          this.form.estimated_start_date = dates[0].format('YYYY-MM-DD')
          this.form.estimated_end_date = dates[1].format('YYYY-MM-DD')
        } else {
          this.form.estimated_start_date = null
          this.form.estimated_end_date = null
        }
      },
      disabledDate(current) {
        // Can not select days before today and today
        return current && current < moment().startOf('day');
      },
      /**
       * @description 获取初始人员列表 树状
       */
      async getInitialPersonListTree() {
        this.personLoading = true
        try {
          const res = await apiPersonGetAllListTree({})
          if (res.code === 200) {
            console.log(res.data)
            this.personListTree1 = [...res.data]
          } else {
            this.$message.error(res.message)
          }
        } catch (err) {
          this.$message.error(err.toString())
        }
        this.personLoading = false
      },
      /**
       * @description 获取审批人员列表 树状
       */
      async getFindApproversByLevelTree() {
        this.personLoading = true
        try {
          const res1 = await apiFindApproversByLevelTree({
            can_approve_level: 1
          })
          if (res1.code === 200) {
            this.approversByLevelTree1 = [...res1.data]
          } else {
            this.$message.error(res1.message)
          }
          const res2 = await apiFindApproversByLevelTree({
            can_approve_level: 2
          })
          if (res2.code === 200) {
            this.approversByLevelTree2 = [...res2.data]
          } else {
            this.$message.error(res2.message)
          }
        } catch (err) {
          this.$message.error(err.toString())
        }
        this.personLoading = false
      },
      handleApprover1Change(value, label, extra) {
        this.approver1Name = label[0]
        setTimeout(() => {
          this.approver1 = value
        }, 100)

      },
      handleApprover2Change(value, label, extra) {
        this.approver2Name = label[0]
        setTimeout(() => {
          this.approver2 = value
        }, 100)
      },
      /**
       * @description 提交表单
       */
      async handleSubmit() {
        console.log(this.form)
        this.$refs.form.validate(async valid => {
          console.log(valid)
          if (!this.approver1) {
            this.$message.info('请选择一级审批人')
            return
          }
          this.form.output_types = []
          this.output_types_list.map(item => {
            if (item.checked) {
              this.form.output_types.push(item.value)
            }
          })
          if (this.form.output_types.length == 0) {
            this.$message.info('产出类型')
            return
          }
          if (valid) {
            this.submitting = true
            try {
              let approvers = []
              approvers.push({
                level: 1,
                approver_id: this.approver1
              })
              if (this.approver2) {
                approvers.push({
                  level: 2,
                  approver_id: this.approver2
                })
              }

              const formData = {
                title: this.form.title,
                content: this.form.content,
                applicant_id: this.personInfo.person_id,
                work_members: this.form.work_members.join(),
                estimated_start_date: this.form.estimated_start_date,
                estimated_end_date: this.form.estimated_end_date,
                approvers,
                output_types: this.form.output_types
              }
              console.log(formData)
              const res = await apiApprovalCreate(formData)
              if (res.code === 200) {
                this.$message.success('报题提交成功！')
                this.handleReset()
              } else {
                this.$message.error(res.message)
              }
            } catch (err) {
              this.$message.error(err.toString())
            }
            this.submitting = false
          }
        })
      },
      /**
       * @description 重置表单
       */
      handleReset() {
        this.$refs.form.resetFields()
        this.form = {
          title: '',
          work_members: [],
          content: '',
          output_types: [],
          estimated_start_date: null,
          estimated_end_date: null,
          dateRange: []
        }
        this.approver1 = null;
        this.approver1Name = null;
        this.approver2 = null;
        this.approver2Name = null;
        this.output_types_list = [{
          value: 1,
          label: '新媒体图文',
          checked: false
        }, {
          value: 2,
          label: '新媒体视频',
          checked: false
        }, {
          value: 3,
          label: '广播电视类',
          checked: false
        }]
        this.getInitialPersonListTree()
      }
    }
  }
</script>

<style lang="less" scoped>
  .add-approval {
    display: flex;
    // flex-direction: column;
    // align-items: center;
    padding: 24px;

    .header {
      margin-bottom: 12px;
      text-align: center;

      h2 {
        margin: 0;
        font-size: 20px;
        font-weight: 500;
      }
    }

    .content {
      width: 100%;
      // max-width: 800px;
      background: #fff;
      padding: 24px 128px;
      border-radius: 4px;
      // box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);

      .a-timeline-content {
        /deep/ .ant-timeline-item-content {
          transform: translateY(-24px);
          margin-left: 32px;
        }
      }

      .submit-content {
        left: 50%;
        /* width: 100%; */
        position: absolute;
        transform: translateX(-50%);
      }

    }
  }
</style>